import 'package:flutter/material.dart';
import '../models/mood_type.dart';
import '../constants/app_theme.dart';

/// 情绪选择器组件
/// 用于显示和选择不同的情绪类型
class MoodSelector extends StatefulWidget {
  /// 情绪选择回调
  final Function(MoodType) onMoodSelected;
  
  /// 是否显示标签
  final bool showLabels;
  
  /// 图标大小
  final double size;
  
  /// 是否启用动画
  final bool enableAnimation;
  
  /// 选中的情绪类型
  final MoodType? selectedMood;
  
  /// 是否允许取消选择
  final bool allowDeselect;

  const MoodSelector({
    super.key,
    required this.onMoodSelected,
    this.showLabels = false,
    this.size = 40,
    this.enableAnimation = true,
    this.selectedMood,
    this.allowDeselect = false,
  });

  @override
  State<MoodSelector> createState() => _MoodSelectorState();
}

class _MoodSelectorState extends State<MoodSelector>
    with TickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _scaleAnimation;
  MoodType? _selectedMood;

  @override
  void initState() {
    super.initState();
    _selectedMood = widget.selectedMood;
    
    if (widget.enableAnimation) {
      _animationController = AnimationController(
        duration: const Duration(milliseconds: 200),
        vsync: this,
      );
      
      _scaleAnimation = Tween<double>(
        begin: 1.0,
        end: 1.2,
      ).animate(CurvedAnimation(
        parent: _animationController,
        curve: Curves.elasticOut,
      ));
    }
  }

  @override
  void dispose() {
    if (widget.enableAnimation) {
      _animationController.dispose();
    }
    super.dispose();
  }

  @override
  void didUpdateWidget(MoodSelector oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.selectedMood != oldWidget.selectedMood) {
      setState(() {
        _selectedMood = widget.selectedMood;
      });
    }
  }

  /// 处理情绪选择
  void _handleMoodSelection(MoodType moodType) {
    if (_selectedMood == moodType && widget.allowDeselect) {
      // 取消选择
      setState(() {
        _selectedMood = null;
      });
    } else {
      // 选择新情绪
      setState(() {
        _selectedMood = moodType;
      });
      
      // 播放动画
      if (widget.enableAnimation) {
        _animationController.forward().then((_) {
          _animationController.reverse();
        });
      }
      
      // 触发回调
      widget.onMoodSelected(moodType);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Wrap(
      spacing: 16,
      runSpacing: 16,
      alignment: WrapAlignment.center,
      children: MoodType.values.map((moodType) {
        return _buildMoodItem(moodType);
      }).toList(),
    );
  }

  /// 构建单个情绪项目
  Widget _buildMoodItem(MoodType moodType) {
    final isSelected = _selectedMood == moodType;
    
    Widget child = Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        // 情绪图标
        _buildMoodIcon(moodType, isSelected),
        
        // 情绪标签
        if (widget.showLabels) ...[
          const SizedBox(height: 8),
          _buildMoodLabel(moodType, isSelected),
        ],
      ],
    );

    return GestureDetector(
      onTap: () => _handleMoodSelection(moodType),
      child: widget.enableAnimation && isSelected
          ? AnimatedBuilder(
              animation: _scaleAnimation,
              builder: (context, child) {
                return Transform.scale(
                  scale: _scaleAnimation.value,
                  child: child,
                );
              },
              child: child,
            )
          : child,
    );
  }

  /// 构建情绪图标
  Widget _buildMoodIcon(MoodType moodType, bool isSelected) {
    return AnimatedContainer(
      duration: const Duration(milliseconds: 200),
      width: widget.size + (isSelected ? 8 : 0),
      height: widget.size + (isSelected ? 8 : 0),
      decoration: BoxDecoration(
        color: isSelected 
            ? moodType.color.withValues(alpha: 0.2)
            : Colors.transparent,
        shape: BoxShape.circle,
        border: isSelected
            ? Border.all(
                color: moodType.color,
                width: 2,
              )
            : null,
        boxShadow: isSelected
            ? [
                BoxShadow(
                  color: moodType.color.withValues(alpha: 0.3),
                  blurRadius: 8,
                  spreadRadius: 2,
                ),
              ]
            : null,
      ),
      child: Center(
        child: Text(
          moodType.emoji,
          style: TextStyle(
            fontSize: widget.size * 0.6,
          ),
        ),
      ),
    );
  }

  /// 构建情绪标签
  Widget _buildMoodLabel(MoodType moodType, bool isSelected) {
    return AnimatedDefaultTextStyle(
      duration: const Duration(milliseconds: 200),
      style: TextStyle(
        fontSize: 12,
        fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
        color: isSelected 
            ? moodType.color 
            : AppTheme.textSecondaryColor,
      ),
      child: Text(
        moodType.displayName,
        textAlign: TextAlign.center,
      ),
    );
  }
}

/// 水平情绪选择器
/// 用于在有限空间内显示情绪选择
class HorizontalMoodSelector extends StatelessWidget {
  /// 情绪选择回调
  final Function(MoodType) onMoodSelected;
  
  /// 选中的情绪类型
  final MoodType? selectedMood;
  
  /// 图标大小
  final double size;

  const HorizontalMoodSelector({
    super.key,
    required this.onMoodSelected,
    this.selectedMood,
    this.size = 32,
  });

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: Row(
        children: MoodType.values.map((moodType) {
          final isSelected = selectedMood == moodType;
          
          return Padding(
            padding: const EdgeInsets.only(right: 12),
            child: GestureDetector(
              onTap: () => onMoodSelected(moodType),
              child: AnimatedContainer(
                duration: const Duration(milliseconds: 200),
                width: size + (isSelected ? 8 : 0),
                height: size + (isSelected ? 8 : 0),
                decoration: BoxDecoration(
                  color: isSelected 
                      ? moodType.color.withValues(alpha: 0.2)
                      : AppTheme.surfaceColor,
                  shape: BoxShape.circle,
                  border: Border.all(
                    color: isSelected 
                        ? moodType.color 
                        : AppTheme.dividerColor,
                    width: isSelected ? 2 : 1,
                  ),
                  boxShadow: isSelected
                      ? [
                          BoxShadow(
                            color: moodType.color.withValues(alpha: 0.3),
                            blurRadius: 4,
                            spreadRadius: 1,
                          ),
                        ]
                      : null,
                ),
                child: Center(
                  child: Text(
                    moodType.emoji,
                    style: TextStyle(
                      fontSize: size * 0.5,
                    ),
                  ),
                ),
              ),
            ),
          );
        }).toList(),
      ),
    );
  }
}

/// 网格情绪选择器
/// 用于在较大空间内以网格形式显示情绪选择
class GridMoodSelector extends StatelessWidget {
  /// 情绪选择回调
  final Function(MoodType) onMoodSelected;
  
  /// 选中的情绪类型
  final MoodType? selectedMood;
  
  /// 图标大小
  final double size;
  
  /// 列数
  final int crossAxisCount;

  const GridMoodSelector({
    super.key,
    required this.onMoodSelected,
    this.selectedMood,
    this.size = 48,
    this.crossAxisCount = 3,
  });

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: crossAxisCount,
        crossAxisSpacing: 16,
        mainAxisSpacing: 16,
        childAspectRatio: 1,
      ),
      itemCount: MoodType.values.length,
      itemBuilder: (context, index) {
        final moodType = MoodType.values[index];
        final isSelected = selectedMood == moodType;
        
        return GestureDetector(
          onTap: () => onMoodSelected(moodType),
          child: AnimatedContainer(
            duration: const Duration(milliseconds: 200),
            decoration: BoxDecoration(
              color: isSelected 
                  ? moodType.color.withValues(alpha: 0.1)
                  : AppTheme.surfaceColor,
              borderRadius: BorderRadius.circular(16),
              border: Border.all(
                color: isSelected 
                    ? moodType.color 
                    : AppTheme.dividerColor,
                width: isSelected ? 2 : 1,
              ),
              boxShadow: isSelected
                  ? [
                      BoxShadow(
                        color: moodType.color.withValues(alpha: 0.2),
                        blurRadius: 8,
                        spreadRadius: 2,
                      ),
                    ]
                  : [
                      BoxShadow(
                        color: Colors.black.withValues(alpha: 0.05),
                        blurRadius: 4,
                        offset: const Offset(0, 2),
                      ),
                    ],
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  moodType.emoji,
                  style: TextStyle(
                    fontSize: size * 0.6,
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  moodType.displayName,
                  style: TextStyle(
                    fontSize: 12,
                    fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                    color: isSelected 
                        ? moodType.color 
                        : AppTheme.textSecondaryColor,
                  ),
                  textAlign: TextAlign.center,
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}